#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include <fstream>
#include "log.hpp"

using namespace LogModule;

const std::string gpath = "./";
const std::string gdictname = "dict.txt";
const std::string defaultgap = ": ";

class Dictionary
{
private:
    bool Dictdownload()
    {
        std::string file = _path + _filename;
        std::ifstream in(file.c_str());
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file " << file << "error";
            return false;
        }
        std::string line;
        while (getline(in, line))
        {
            // student: 学生
            std::string word;
            std::string value;
            if (SplitString(line ,&word ,&value ,defaultgap))
            {
                _dictionary.insert(std::make_pair(word ,value));
            }
        }

        in.close();
        return true;
    }
    // student: 学生
    bool SplitString(std::string line, std::string *key, std::string *value, std::string gap)
    {
        auto pos = line.find(gap);
        if (pos == std::string::npos) return false;
        *key = line.substr(0, pos);
        *value = line.substr(pos + gap.size());
        if (key->empty() || value->empty())
            return false;

        return true;
    }

public:
    Dictionary(const std::string &path = gpath, const std::string &filename = gdictname)
        : _path(path),
          _filename(filename)
    {
        Dictdownload();
        Print();
    }

    std::string Translate(std::string key)
    {
        auto item =_dictionary.find(key);
        if(item==_dictionary.end()) 
            return "NONE";

        return item->second; //_dictionary[key]
    }

    void Print()
    {
        for(auto &item : _dictionary)
        {
            std::cout << item.first << ":" << item.second<< std::endl;
        }
    }

    ~Dictionary()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dictionary;
    std::string _path;
    std::string _filename;
};